import {Component, ViewEncapsulation, Input, ViewChild} from '@angular/core';
import {UserService} from '../../../../services/app.user';
import {BaThemeSpinner}  from '../../../../theme/services';
import {Utility} from '../../../../services/app.utility';
import {AuthenticationHelper} from '../../../../app.authentication';
import {Router} from '@angular/router';
import {LocalDataSource} from 'ng2-smart-table';
import {Constants} from '../../../../common/app.constants';
declare let toastr: any;
declare let $: any;

@Component({
  selector: 'activity',
  encapsulation: ViewEncapsulation.None,
  templateUrl: './activities.html',
  styleUrls: ['./activities.scss'],
})

export class Activity {

  public start:any;
  public end:any;
  public check:any;
  @Input()
  data = [];
  constants: Constants;
  query: string = '';
  skipItem: number = 0;
  removePagination: boolean = true;
//  @ViewChild('userLogTable') userLogTable: Ng2SmartTableComponent;
  settings = {
    add: {
      addButtonContent: '<i class="ion-ios-plus-outline"></i>',
      createButtonContent: '<i class="ion-checkmark"></i>',
      cancelButtonContent: '<i class="ion-close"></i>',
    },
    edit: {
      editButtonContent: '<i class="ion-edit"></i>',
      saveButtonContent: '<i class="ion-checkmark"></i>',
      cancelButtonContent: '<i class="ion-close"></i>',
    },
    delete: {
      deleteButtonContent: '<i class="ion-trash-a"></i>',
      confirmDelete: true
    },
    columns: {
      createdAt: {
        title: 'Created At',
        type: 'string'
      }, name: {
        title: 'Name',
        type: 'string'
      },
      action: {
        title: 'Activity Type',
        type: 'string'
      },
      title: {
        title: 'Title',
        type: 'string'
      }
    }
  };

  source: LocalDataSource = new LocalDataSource();

  public userId: any;
  public userName: any;
  toDate: string = '';
  fromDate: string = '';
  myDatePickerOptions: any = {};

  constructor(private userService: UserService, private spinner: BaThemeSpinner, public utility: Utility, private router: Router, private authentication: AuthenticationHelper) {
    this.constants = new Constants();
    let todayDate = new Date();
    this.myDatePickerOptions = {
      todayBtnTxt: 'Today',
      dateFormat: 'dd/mm/yyyy',
      firstDayOfWeek: 'mo',
      sunHighlight: true,
      inline: false,
      disableSince: {
        year: todayDate.getFullYear(),
        month: todayDate.getUTCMonth() + 1, day: todayDate.getDate() + 1
      },
      selectionTxtFontSize: '16px'
    };
    this.start = 0;
    this.check = 0;

    // start timer for timestamp
    this.startCount();
  }

  // Call for get user info after load view
  ngAfterViewInit() {
    this.data = [];
    this.fromDate = this.utility.getFormattedDateForTree(this.utility.getMonthsAgoDate(1));
    this.toDate = this.utility.getFormattedDateForTree(new Date());
    this.source.load(this.data);
    this.userService.getuserInfo().subscribe(
      data => this.userInfoSuccess(data),
      error => {
      }
    );
  }

  // Call for get user info successfully
  public userInfoSuccess(data) {
    console.log("activity");
    this.spinner.showProgress();
    this.userId = data._id;
    if (this.utility.userDetailFlag) {
      this.logs();
      this.userName = this.utility.userDetails.name;
    } else {
      this.logs();
      this.userName = data.firstName;
    }
    this.utility.userDetailFlag = false;
  }

  // funtion for Get user log data using API call
  public logs() {
    if (this.utility.userDetailFlag) {
      this.userId = this.utility.userDetails._id;
    }
    let input = {
      "fromDate": this.fromDate,
      "skipItem": this.skipItem,
      "itemsperPage": "10",
      "toDate": this.toDate,
      "userId": this.userId
    };
    this.userService.getuserActivityData(input).subscribe(
      data => {
        this.getData(data);
      });
  }

  // Function for received log data and send to smart table
  public getData(data) {
    if (data.activityCount <= this.skipItem) {
      this.removePagination = false;
    }
    if (data.activityList) {
      if (this.skipItem == 0) {
        this.data = [];
      }
      data.activityList.forEach(item => {
        let data = {
          createdAt: this.utility.getFormattedDate(item.createdAt),
          title: item.title,
          action: item.activityType,
          name: item.name
        };
        this.data.push(data);
        //
      });
      this.source.load(this.data);
      this.source.reset();
      this.source.setPage(this.skipItem);
    }
    this.spinner.hideProgress();
  }

  getLogData() {
    this.skipItem += 10;
    this.logs();
  }

  // Function for get CSV from server
  public getCSV(event) {
    let input = {
      "fromDate": this.utility.getFormattedDateForTree(this.utility.getMonthsAgoDate(1)),
      "toDate": this.utility.getFormattedDateForTree(new Date()),
      'userId': this.userId,
      'csvType': 'activities'
    };
    if (this.utility.userDetailFlag) {
      input.userId = this.utility.userDetails._id;
    } else {
      delete input.userId;
    }
    this.userService.getLogAllCSV(input).subscribe(
      data => this.getCSVSuccess(data),
      error => {
      }
    );
  }

  // Function for download user log data CSV
  public getCSVSuccess(data) {
    let url = this.constants.LINK;
    let fileName = data.substr(1, data.length);
    let urlOfFile = url + '' + fileName;
    window.open(urlOfFile, '_blank');
  }

  onFromDateChanged(event: any) {
    if (event.formatted === '') {

    } else {
      let day, month;
      day = event.date.day;
      month = event.date.month;
      if (event.date.month < 10) {
        month = 0 + '' + event.date.month;
      }
      if (event.date.day < 10) {
        day = 0 + '' + event.date.day;
      }

      this.fromDate = day + '/' + month + '/' + event.date.year;
    }
  }

  // Fuction for change To date of datepicker
  onToDateChanged(event: any) {
    if (event.formatted === '') {

    } else {
      let day, month;
      day = event.date.day;
      month = event.date.month;
      if (event.date.month < 10) {
        month = 0 + '' + event.date.month;
      }
      if (event.date.day < 10) {
        day = 0 + '' + event.date.day;
      }

      this.toDate = day + '/' + month + '/' + event.date.year;
    }
  }

  searchActivities($event) {
    this.skipItem = 0;
    this.logs();
  }

  // To call every 1 sec for count how much time we spent on this page
  public  timedCount() {
    this.start = this.start + 1;
    this.end = setTimeout(() => {
      this.timedCount()
    }, 1);
  }

  // To function for start timstamp count
  public startCount() {
    if (!this.check) {
      this.check = 1;
      this.timedCount();
    }
  }

  // To function for stop timstamp count
  public stopCount() {
    clearTimeout(this.end);
    this.check = 0;
  }

  ngOnDestroy() {
    // To stop count function call
    this.stopCount();

    // API call for tract navigation sequence
    let seq = {
      sequence: {
        "pageName": 'admin/activity',
        "timeSpent": this.start
      }

    };
    this.userService.setUrlSeq(seq).subscribe();
  }
}
